package com.hjm.project.agentInfo.AgentCountData.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.google.common.collect.Lists;
import com.hjm.common.utils.DateUtils;
import com.hjm.common.utils.LogUtils;
import com.hjm.common.utils.StringUtils;
import com.hjm.project.agentInfo.AgentCountData.domain.AgentCountData;
import com.hjm.project.agentInfo.AgentCountData.mapper.AgentCountDataMapper;
import com.hjm.project.agentInfo.AgentCountData.service.AgentCountDataService;
import com.hjm.project.agentInfo.AgentCountData.utils.GradeMoney;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfo;
import com.hjm.project.agentInfo.agentInfo.mapper.AgentInfoMapper;
import com.hjm.project.gearsRecord.gearsRecord.domain.GearsRecord;
import com.hjm.project.gearsRecord.gearsRecord.mapper.GearsRecordMapper;
import com.hjm.project.gears_info.domain.GearsInfo;
import com.hjm.project.gears_info.mapper.GearsInfoMapper;
import com.hjm.project.statistical.standard.domain.AgentMonthStandard;
import com.hjm.project.statistical.standard.mapper.AgentMonthStandardMapper;
import com.hjm.project.system.sysConfigJob.domain.SysConfigJob;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import com.hjm.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

/**
 * 代理商交易额统计Service业务层处理
 *
 * @author maker-platform
 * @date 2021-03-05
 */
@Service
public class AgentCountDataServiceImpl implements AgentCountDataService{



    @Resource
    private AgentCountDataMapper agentCountDataMapper;

    //@Resource
   // private Trade


    @Resource
    private GearsRecordMapper gearsRecordMapper; //档位记录

    @Resource
    private GearsInfoMapper gearsInfoMapper;     //档位信息

    @Resource
    private AgentInfoMapper agentInfoMapper;   //代理信息

    @Resource
    private AgentMonthStandardMapper agentMonthStandardMapper; //达标台均

    /**
     * 查询代理商交易额统计
     *
     * @param id 代理商交易额统计ID
     * @return 代理商交易额统计
     */
    @Override
    public AgentCountData selectAgentTransactionAmountById(Integer id)
    {
        return agentCountDataMapper.selectAgentTransactionAmountById(id);
    }

    /**
     * 查询代理商交易额统计列表
     *
     * @param agentTransactionAmount 代理商交易额统计
     * @return 代理商交易额统计
     */
    @Override
    public List<AgentCountData> selectAgentTransactionAmountList(AgentCountData agentTransactionAmount)
    {
        return agentCountDataMapper.selectAgentTransactionAmountList(agentTransactionAmount);
    }
    public AgentCountData selectMoneySum(AgentCountData agentTransactionAmount)
    {
        return agentCountDataMapper.selectMoneySum(agentTransactionAmount);
    }

    /**
     * 新增代理商交易额统计
     *
     * @param agentTransactionAmount 代理商交易额统计
     * @return 结果
     */
    @Override
    public int insertAgentTransactionAmount(AgentCountData agentTransactionAmount)
    {
        return agentCountDataMapper.insertAgentTransactionAmount(agentTransactionAmount);
    }

    /**
     * 修改代理商交易额统计
     *
     * @param agentTransactionAmount 代理商交易额统计
     * @return 结果
     */
    @Override
    public int updateAgentTransactionAmount(AgentCountData agentTransactionAmount)
    {
        return agentCountDataMapper.updateAgentTransactionAmount(agentTransactionAmount);
    }

    /**
     * 删除代理商交易额统计对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAgentTransactionAmountByIds(String ids)
    {
        return agentCountDataMapper.deleteAgentTransactionAmountByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除代理商交易额统计信息
     *
     * @param id 代理商交易额统计ID
     * @return 结果
     */
    @Override
    public int deleteAgentTransactionAmountById(Integer id)
    {
        return agentCountDataMapper.deleteAgentTransactionAmountById(id);
    }



    /**
     * 统计每个代理的每日交易总额
     * @Param [date 自定义统计日期]
     * @Return void
     */
    @Transactional
    public void agentTradingAll(SysConfigJob configJob) throws Exception {
        try{
            long start = System.currentTimeMillis();
            LogUtils.logInfo(DateUtils.getTime() + " 统计每日汇总开始");
            AgentCountData amount = new AgentCountData();
            if (configJob.getConfigId() != null) {
                String configValue = configJob.getConfigValue();
                amount.setCreateDate(DateUtils.getDay(DateUtils.YYYY_MM_DD,1,configValue));
                amount.setTradeDate(configValue);
            } else {
                amount.setTradeDate(DateUtils.getDay(DateUtils.YYYY_MM_DD,-1,DateUtils.getDate()));
                amount.setCreateDate(DateUtils.getDate());
            }
            //统计前删除当天数据
            agentCountDataMapper.deleteData(amount);

            //交易所属月份
            amount.setTradeMonth(amount.getTradeDate().substring(0,7));

            //初始化所有代理商信息
            List<AgentCountData> list = new ArrayList<>();
            List<AgentInfo> allAgentList = agentInfoMapper.selectOneAgentNumNew(null);
            for (AgentInfo agentInfo : allAgentList) {
                LogUtils.logInfo("当前代理商:" + agentInfo.getAgentNum());
                amount.setAgentNum(agentInfo.getAgentNum());
                //统计gb交易
                AgentCountData gbInfo = agentCountDataMapper.selectGbTradeInfo(amount);
                if (gbInfo == null) {
                    continue;
                }
                list.add(gbInfo);
                if (list.size() >= 500) {
                    agentCountDataMapper.insertBatch(list);
                    list.clear();
                }
            }
            if (list.size() > 0) {
                agentCountDataMapper.insertBatch(list);
                list.clear();
            }

            long end = System.currentTimeMillis();
            LogUtils.logInfo(DateUtils.getTime() + " 统计每日汇总结束,耗时:" + (end-start)/1000);
        }catch (Exception e){
            LogUtils.logInfo("统计异常:" + DateUtils.getTime() + " " +e);
            LogUtils.logInfo(DateUtils.getTime() + " 统计每日汇总异常");
            throw e;
        }
    }


    /**
     * 个人档位
     * @Param []
     * @Return void
     */
    @Transactional
    public void agentTradinMonth(SysConfigJob configJob) throws Exception {
        try{
            long start = System.currentTimeMillis();
            LogUtils.logInfo(DateUtils.getTime() + " 统计代理个人档位开始");
            LogUtils.logInfo("开始初始化档位信息");
            List<GearsInfo> gearsInfos = gearsInfoMapper.selectGearsInfoList(null);
            GradeMoney.initGrade(gearsInfos);
            LogUtils.logInfo("初始化档位信息成功");
            AgentCountData agentCountData = new AgentCountData();
            if (configJob.getConfigId() != null) {
                agentCountData.setTradeMonth(DateUtils.getDay(DateUtils.YYYY_MM,-1,configJob.getConfigValue()));
            } else {
                agentCountData.setTradeMonth(DateUtils.getDay(DateUtils.YYYY_MM,-1,DateUtils.getDateYYYY_MM()));
            }
            //获取月交易数据
            List<AgentCountData> dataList = agentCountDataMapper.selectSumMoney(agentCountData);
            if (CollectionUtils.isNotEmpty(dataList)) {
                for (AgentCountData countData : dataList) {
                    BigDecimal amount = countData.getAmount();
                    //代理当前个人档位
                    String grade = countData.getGrade();

                    //根据交易量统计的档位
                    String currentGrade = "";
                    //代理的交易总额
                    if (amount.compareTo(GradeMoney.V1) < 1) {
                        currentGrade = "1";
                    } else if (amount.compareTo(GradeMoney.V1) > -1 && amount.compareTo(GradeMoney.V2) == -1){
                        currentGrade = "2";
                    } else if (amount.compareTo(GradeMoney.V2) > -1 && amount.compareTo(GradeMoney.V3) == -1){
                        currentGrade = "3";
                    } else if (amount.compareTo(GradeMoney.V3) > -1 && amount.compareTo(GradeMoney.V4) == -1){
                        currentGrade = "4";
                    } else if (amount.compareTo(GradeMoney.V4) > -1 && amount.compareTo(GradeMoney.V5) == -1){
                        currentGrade = "5";
                    } else if (amount.compareTo(GradeMoney.V5) > -1 && amount.compareTo(GradeMoney.V6) == -1){
                        currentGrade = "6";
                    } else if (amount.compareTo(GradeMoney.V6) > -1 && amount.compareTo(GradeMoney.V7) == -1){
                        currentGrade = "7";
                    } else if (amount.compareTo(GradeMoney.V7) > -1 && amount.compareTo(GradeMoney.V8) == -1){
                        currentGrade = "8";
                    } else if (amount.compareTo(GradeMoney.V8) > -1 && amount.compareTo(GradeMoney.V9) == -1){
                        currentGrade = "9";
                    } else if (amount.compareTo(GradeMoney.V9) > -1 && amount.compareTo(GradeMoney.V10) == -1){
                        currentGrade = "10";
                    } else if (amount.compareTo(GradeMoney.V10) > -1){
                        currentGrade = "10";
                    }
                    //查看当前代理的扶持信息
                    //String endDate = countData.getEndDate();
                    //查看扶持档位是否过期（true已过期 false 未过期） 未过期 , 交易也达不到量 不降档
                    //boolean isEnd = endDate == null ? true : DateUtils.compareDate(DateUtils.YYYY_MM_DD,endDate,DateUtils.getDate());
                     //扶持档位不过期 并且大于个人档位
                    String grades = grade.replaceAll("V","");

                     //交易量档位大于 当前代理的本身档位 做升档操作
                     if (Integer.parseInt(currentGrade) != Integer.parseInt(grades)/* && isEnd*/) {

                         //交易量的档位信息
                         GearsInfo afterGearsInfo = new GearsInfo();
                         afterGearsInfo.setGrade("V"+currentGrade);
                         GearsInfo afterInfo = gearsInfoMapper.selectGearsInfoList(afterGearsInfo).get(0);

                         //当前代理的档位信息
                         GearsInfo beforGearsInfo = new GearsInfo();
                         beforGearsInfo.setGrade(grade);
                         GearsInfo beforInfo = gearsInfoMapper.selectGearsInfoList(beforGearsInfo).get(0);

                         GearsRecord gearsRecord = new GearsRecord();
                         gearsRecord.setAddMan("系统定时");
                         gearsRecord.setBefor(beforInfo.getGrade());
                         gearsRecord.setBeforDs(beforInfo.getDs());
                         gearsRecord.setAfter(afterInfo.getGrade());
                         gearsRecord.setAfterDs(afterInfo.getDs());
                         gearsRecord.setAgentName(countData.getAgentName());
                         gearsRecord.setAgentNum(countData.getAgentNum());
                         gearsRecord.setUpdateDate(DateUtils.getTime());
                         gearsRecord.setType("1");
                         gearsRecordMapper.insertGearsRecord(gearsRecord);

                         //更新档位信息
                         AgentInfo agentInfo = new AgentInfo();
                         agentInfo.setAgentNum(countData.getAgentNum());
                         agentInfo.setGrade("V"+currentGrade);
                         agentInfoMapper.updateAgent(agentInfo);
                         //交易量档位小于 当前档位 （降档-前提是扶持档位过期）
                     }
                     /*****************************团队档位*******************************/
                    //当前代理的团队档位
                    String teamGrade = countData.getTeamGrade();
                   //获取当前代理下所有的V5
                    AgentInfo agentInfo = new AgentInfo();
                    agentInfo.setAgentNum(countData.getAgentNum());
                    agentInfo.setGrade("V5");
                    int count = agentInfoMapper.selectBelongAgent(agentInfo);

                    if (amount.compareTo(GradeMoney.V1) < 1) {
                        currentGrade = "1";
                    } else if (amount.compareTo(GradeMoney.V1) > -1 && amount.compareTo(GradeMoney.V2) == -1){
                        currentGrade = "2";
                    } else if (amount.compareTo(GradeMoney.V2) > -1 && amount.compareTo(GradeMoney.V3) == -1){
                        currentGrade = "3";
                    } else if (amount.compareTo(GradeMoney.V3) > -1 && amount.compareTo(GradeMoney.V4) == -1){
                        currentGrade = "4";
                    } else if (amount.compareTo(GradeMoney.V4) > -1 && amount.compareTo(GradeMoney.V5) == -1){
                        currentGrade = "5";
                    } else if (amount.compareTo(GradeMoney.V5) > -1 && amount.compareTo(GradeMoney.V6) == -1){
                        if (count >= 1) {
                            currentGrade = "6";
                        } else {
                            currentGrade = "5";
                        }
                    } else if (amount.compareTo(GradeMoney.V6) > -1 && amount.compareTo(GradeMoney.V7) == -1){
                        if (count >= 3) {
                            currentGrade = "7";
                        } else {
                            currentGrade = "6";
                        }
                    } else if (amount.compareTo(GradeMoney.V7) > -1 && amount.compareTo(GradeMoney.V8) == -1){
                        if (count >= 5) {
                            currentGrade = "8";
                        } else {
                            currentGrade = "7";
                        }
                    } else if (amount.compareTo(GradeMoney.V8) > -1 && amount.compareTo(GradeMoney.V9) == -1){
                        if (count >= 7) {
                            currentGrade = "9";
                        } else {
                            currentGrade = "8";
                        }
                    } else if (amount.compareTo(GradeMoney.V9) > -1 && amount.compareTo(GradeMoney.V10) == -1){
                        if (count >= 10) {
                            currentGrade = "10";
                        } else {
                            currentGrade = "9";
                        }
                    }  else if (amount.compareTo(GradeMoney.V10) > -1){
                        if (count >= 10) {
                            currentGrade = "10";
                        } else {
                            currentGrade = "9";
                        }
                    }

                    //默认V1
                    Integer tgNum = 1;
                    if (StringUtils.isNotEmpty(teamGrade)) {
                        tgNum = Integer.parseInt(teamGrade.replaceAll("V",""));
                    }
                    //升档 和 降档(团队)
                    if ((Integer.parseInt(currentGrade) != tgNum /* && isEnd*/)){
                        //交易量的档位信息
                        GearsInfo afterGearsInfo = new GearsInfo();
                        afterGearsInfo.setGrade("V"+currentGrade);
                        GearsInfo afterInfo = gearsInfoMapper.selectGearsInfoList(afterGearsInfo).get(0);

                        //当前代理的档位信息
                        GearsInfo beforGearsInfo = new GearsInfo();
                        beforGearsInfo.setGrade(grade);
                        GearsInfo beforInfo = gearsInfoMapper.selectGearsInfoList(beforGearsInfo).get(0);
                        GearsRecord gearsRecord = new GearsRecord();
                        gearsRecord.setAddMan("系统定时");
                        gearsRecord.setBefor(beforInfo.getGrade());
                        gearsRecord.setBeforDs(beforInfo.getDs());
                        gearsRecord.setAfter(afterInfo.getGrade());
                        gearsRecord.setAfterDs(afterInfo.getDs());
                        gearsRecord.setAgentName(countData.getAgentName());
                        gearsRecord.setAgentNum(countData.getAgentNum());
                        gearsRecord.setUpdateDate(DateUtils.getTime());
                        gearsRecord.setType("2");
                        gearsRecordMapper.insertGearsRecord(gearsRecord);

                        //更新档位信息
                        AgentInfo agent = new AgentInfo();
                        agent.setAgentNum(countData.getAgentNum());
                        agent.setTeamGrade("V"+currentGrade);
                        agentInfoMapper.updateAgent(agent);
                    }
                }
            } else {
                LogUtils.logInfo(DateUtils.getTime() + " 未查询到数据");
            }
            long end = System.currentTimeMillis();
            LogUtils.logInfo(DateUtils.getTime() + " 统计代理个人档位结束,耗时:" + (end-start)/1000);
        }catch (Exception e){
            LogUtils.logInfo("统计个人档位异常:" + DateUtils.getTime() + " " +e);
            LogUtils.logInfo(DateUtils.getTime() + " 统计代理个人档位结束");
            throw e;
        }
    }


    /**
     * 月达标台均
     * @Param []
     * @Return void
     */
    public void monthStandard(SysConfigJob configJob) throws Exception {
        try{
            String date = null;
            if (configJob.getConfigId() == null) {
                date = DateUtils.getDay(DateUtils.YYYY_MM_DD,-1,DateUtils.getDate());
            } else {
                date = configJob.getConfigValue();
            }
            String month = DateUtils.getDay(DateUtils.YYYY_MM,0,date);
            agentMonthStandardMapper.deleteAgentMonthStandardByDate(month);
            //初始化所有代理商信息
            AgentInfo allAgent = new AgentInfo();
            allAgent.setAgentStatus("0");
            List<AgentInfo> allAgentList = agentInfoMapper.selectOneAgentNum(allAgent);
            List<AgentMonthStandard> standardList = new ArrayList<>();
            for (AgentInfo agentInfo : allAgentList) {
                //获取每个代理的达标台均
                AgentMonthStandard standard = new AgentMonthStandard();
                standard.setAgentNum(agentInfo.getAgentNum());
                standard.setAddDate(date);
                standard.setMonthDay(month);
                AgentMonthStandard standardOne = agentMonthStandardMapper.selectMontSum(standard);
                standardOne.setAddMan("SYSTEM");
                standardOne.setDqType(4);
                standardOne.setAddDate(date);
                standardOne.setMonthDay(month);
                standardOne.setMoney(standardOne.getMoney() == null ? new BigDecimal("0") : standardOne.getMoney());
                standardOne.setStandardMoney(standardOne.getStandardMoney() == null ? new BigDecimal("0") : standardOne.getStandardMoney());
                standardOne.setActiveCount(standardOne.getActiveCount() == null ? 0 : standardOne.getActiveCount());
                standardOne.setNote("系统定时");
                standardList.add(standardOne);
            }
            List<List<AgentMonthStandard>> partition = Lists.partition(standardList, 500);
            for (List<AgentMonthStandard> agentMonthStandards : partition) {
                //批量新增
                int i = agentMonthStandardMapper.insertAgentMonthStandardBatch(agentMonthStandards);
                if (i <= 0) {
                    LogUtils.logInfo("统计失败:" + DateUtils.getTime());
                }
            }




        }catch (Exception e){
            LogUtils.logInfo("统计异常:" + DateUtils.getTime() + " " +e);
            LogUtils.logInfo(DateUtils.getTime() + " 统计代理每月结束");
            throw  e;
        }
    }
}
